
from rest_framework import serializers
from .models import ChatSessionModel, ChatMessageModel
from apps.user.serializers import UserProfileSerializer
from apps.project.serializers import ProjectListSerializer


class ChatMessageSerializer(serializers.ModelSerializer):
    """聊天消息序列化器"""
    
    class Meta:
        model = ChatMessageModel
        fields = ['id', 'role', 'content', 'status', 'created_at', 
                 'generated_markdown', 'token_usage']
        read_only_fields = ['id', 'created_at', 'status', 'generated_markdown', 
                           'token_usage']


class ChatSessionSerializer(serializers.ModelSerializer):
    """聊天会话序列化器"""
    user = UserProfileSerializer(read_only=True)
    project = ProjectListSerializer(read_only=True)
    messages = ChatMessageSerializer(many=True, read_only=True)
    message_count = serializers.SerializerMethodField()
    
    class Meta:
        model = ChatSessionModel
        fields = ['id', 'title', 'status', 'created_at', 'updated_at', 
                 'user', 'project', 'messages', 'message_count']
        read_only_fields = ['id', 'created_at', 'updated_at', 'user', 'messages']
    
    def get_message_count(self, obj):
        return obj.messages.count()


class ChatSessionListSerializer(serializers.ModelSerializer):
    """聊天会话列表序列化器"""
    user = UserProfileSerializer(read_only=True)
    project = ProjectListSerializer(read_only=True)
    message_count = serializers.SerializerMethodField()
    last_message_time = serializers.SerializerMethodField()
    
    class Meta:
        model = ChatSessionModel
        fields = ['id', 'title', 'status', 'created_at', 'updated_at', 
                 'user', 'project', 'message_count', 'last_message_time']
    
    def get_message_count(self, obj):
        return obj.messages.count()
    
    def get_last_message_time(self, obj):
        last_message = obj.messages.last()
        return last_message.created_at if last_message else obj.created_at


class ChatMessageCreateSerializer(serializers.ModelSerializer):
    """创建聊天消息序列化器"""
    
    class Meta:
        model = ChatMessageModel
        fields = ['content']
    
    def create(self, validated_data):
        validated_data['session'] = self.context['session']
        validated_data['role'] = 'user'
        validated_data['status'] = 'completed'
        return ChatMessageModel.objects.create(**validated_data)
